package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppClubActivity;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUserActivityRegistration;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.entity.yangyangLeadingEnterprise.dto.ClubActivityDTO;
import com.mdd.common.entity.yangyangLeadingEnterprise.param.ClubActivityParam;
import com.mdd.common.enums.ErrorEnum;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppClubActivityMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserActivityRegistrationMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.cache.TokenLoginCache;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppClubActivityService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppClubActivityCreateValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppClubActivitySearchValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppClubActivityUpdateValidate;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppClubActivityDetailVo;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppClubActivityListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 俱乐部活动实现类
 * @author LikeAdmin
 */
@Service
public class TAppClubActivityServiceImpl implements ITAppClubActivityService {
        
    @Resource
    TAppClubActivityMapper tAppClubActivityMapper;

    @Resource
    TAppUserActivityRegistrationMapper appUserActivityRegistrationMapper;

    /**
     * 俱乐部活动列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<TAppClubActivityListedVo>
     */
    @Override
    public PageResult<TAppClubActivityListedVo> list(PageValidate pageValidate, TAppClubActivitySearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<TAppClubActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        tAppClubActivityMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:activityName@activity_name:str",
            "=:provinceId@province_id:int",
            "=:cityId@city_id:int",
            "=:areaId@area_id:int",
            "=:address:str",
            "=:shouAddress@shou_address:str",
            "=:pic:str",
            "=:introduction:str",
            "=:activityStartTime@activity_start_time:str",
            "=:activityEndTime@activity_end_time:str",
            "=:registrationDeadline@registration_deadline:str",
            "=:dicId@dic_id:int",
            "=:dicType@dic_type:str",
            "=:status:int",
        });

        IPage<TAppClubActivity> iPage = tAppClubActivityMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<TAppClubActivityListedVo> list = new LinkedList<>();
        for(TAppClubActivity item : iPage.getRecords()) {
            TAppClubActivityListedVo vo = new TAppClubActivityListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime().getTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime().getTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 俱乐部活动详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return TAppClubActivity
     */
    @Override
    public TAppClubActivityDetailVo detail(Integer id) {
        TAppClubActivity model = tAppClubActivityMapper.selectOne(
                new QueryWrapper<TAppClubActivity>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TAppClubActivityDetailVo vo = new TAppClubActivityDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 俱乐部活动新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(TAppClubActivityCreateValidate createValidate) {
        TAppClubActivity model = new TAppClubActivity();
        model.setActivityName(createValidate.getActivityName());
        model.setAddress(createValidate.getAddress());
        model.setShouAddress(createValidate.getShouAddress());
        model.setPic(createValidate.getPic());
        model.setIntroduction(createValidate.getIntroduction());
        model.setCreateTime(new Date());
        model.setUpdateTime(new Date());
        model.setActivityStartTime(createValidate.getActivityStartTime());
        model.setActivityEndTime(createValidate.getActivityEndTime());
        model.setDicId(createValidate.getDicId());
        model.setDicType(createValidate.getDicType());
        model.setStatus(createValidate.getStatus());
        tAppClubActivityMapper.insert(model);
    }

    /**
     * 俱乐部活动编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(TAppClubActivityUpdateValidate updateValidate) {
        TAppClubActivity model = tAppClubActivityMapper.selectOne(
                new QueryWrapper<TAppClubActivity>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setActivityName(updateValidate.getActivityName());
        model.setAddress(updateValidate.getAddress());
        model.setShouAddress(updateValidate.getShouAddress());
        model.setPic(updateValidate.getPic());
        model.setIntroduction(updateValidate.getIntroduction());
        model.setUpdateTime(new Date());
        model.setActivityStartTime(updateValidate.getActivityStartTime());
        model.setActivityEndTime(updateValidate.getActivityEndTime());
        model.setDicId(updateValidate.getDicId());
        model.setDicType(updateValidate.getDicType());
        model.setStatus(updateValidate.getStatus());
        tAppClubActivityMapper.updateById(model);
    }

    /**
     * 俱乐部活动删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        TAppClubActivity model = tAppClubActivityMapper.selectOne(
                new QueryWrapper<TAppClubActivity>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        tAppClubActivityMapper.delete(new QueryWrapper<TAppClubActivity>().eq("id", id));
    }

    /**
     * 首页---领企俱乐部活动列表
     * @param param
     * @return
     */
    @Override
    public List<TAppClubActivity> selectList(ClubActivityParam param) {
        String provinceCode = param.getProvinceCode();
        String cityCode = param.getCityCode();
        String areaCode = param.getAreaCode();
        Integer dicId = param.getDicId();
        String dicType = param.getDicType();
        QueryWrapper<TAppClubActivity> wrapper = new QueryWrapper<>();
        if(dicId != null && dicType != null && !dicType.isEmpty()){
            wrapper.eq("dic_id", dicId).eq("dic_type", dicType);
        }
        if(provinceCode!=null && !provinceCode.isEmpty()){
            wrapper.eq("province_code", provinceCode);
        }
        if(cityCode!=null && !cityCode.isEmpty()){
            wrapper.eq("city_code", cityCode);
        }
        if(areaCode!=null && !areaCode.isEmpty()){
            wrapper.eq("area_code", areaCode);
        }
        List<TAppClubActivity> selectList = Optional.ofNullable(tAppClubActivityMapper.selectList(wrapper)).orElse(new ArrayList<>());
        selectList.stream().forEach(item -> {
            updateActivityStatus(item);
        });
        return selectList;
    }

    /**
     * 根据id查询俱乐部活动
     * @param activityId
     * @return
     */
    @Override
    public String selectActivityById(Integer activityId) {
        if (activityId == null) {
            return JsonReturn.fail("必传信息不能为空",40001).toJsonStr();
        }
        Integer userId = TokenLoginCache.get();
        if (userId == null || userId <= 0) {
            return JsonReturn.fail(ErrorEnum.TOKEN_INVALID.getMsg(),ErrorEnum.TOKEN_INVALID.getCode()).toJsonStr();
        }
        ClubActivityDTO dto = new ClubActivityDTO();
        //活动信息
        TAppClubActivity appClubActivity = Optional.ofNullable(tAppClubActivityMapper.selectById(activityId)).orElse(new TAppClubActivity());
        dto.setTAppClubActivity(appClubActivity);
        //报名信息
        QueryWrapper<TAppUserActivityRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_id", activityId);
        wrapper.eq("status", 2);
        List<TAppUserActivityRegistration> registrationList = Optional.ofNullable(appUserActivityRegistrationMapper.selectList(wrapper)).orElse(new ArrayList<>());
        dto.setUserActivityRegistrationList(registrationList);
        dto.setSignUpAmount(registrationList.size());
        //当前用户报名信息
        TAppUserActivityRegistration selectOne = appUserActivityRegistrationMapper.selectOne(new QueryWrapper<TAppUserActivityRegistration>().eq("activity_id", activityId).eq("user_id", userId));
        dto = getActivityShowStatus(appClubActivity, dto, selectOne);
        return JsonReturn.success().put("ClubActivityDTO",dto).toJsonStr();
    }

    public void updateActivityStatus(TAppClubActivity appClubActivity){
        Date signupStartTime = appClubActivity.getSignupStartTime();
        Date signupEndTime = appClubActivity.getSignupEndTime();
        Date activityStartTime = appClubActivity.getActivityStartTime();
        Date activityEndTime = appClubActivity.getActivityEndTime();

        if(signupStartTime!=null && signupEndTime!=null && activityStartTime!=null && activityEndTime!=null){
            if(System.currentTimeMillis()<signupStartTime.getTime()){
                appClubActivity.setStatus(1);
            }
            else if(System.currentTimeMillis()>=signupStartTime.getTime() && System.currentTimeMillis()<=signupEndTime.getTime()){
                appClubActivity.setStatus(2);
            }
            else if (System.currentTimeMillis()>=activityStartTime.getTime() && System.currentTimeMillis()<=activityEndTime.getTime()){
                appClubActivity.setStatus(3);
            } else if (System.currentTimeMillis()>=activityEndTime.getTime()) {
                appClubActivity.setStatus(4);
            }
            tAppClubActivityMapper.updateById(appClubActivity);
        }
    }

    /**
     * 获取活动展示状态
     * @param appClubActivity
     * @param dto
     * @param selectOne
     * @return
     */
    public ClubActivityDTO getActivityShowStatus(TAppClubActivity appClubActivity,ClubActivityDTO dto,TAppUserActivityRegistration selectOne){
        Date signupStartTime = appClubActivity.getSignupStartTime();
        Date signupEndTime = appClubActivity.getSignupEndTime();

        //报名开始前
        if(System.currentTimeMillis()<signupStartTime.getTime()){
            if(selectOne!=null && selectOne.getId()!=null){
                dto.setShowStatus("已设置报名提醒");
            }else {
                dto.setShowStatus("设置报名提醒");
            }
        }
        //报名开始
        else if(System.currentTimeMillis()>=signupStartTime.getTime() && System.currentTimeMillis()<=signupEndTime.getTime()){
            if(selectOne!=null && selectOne.getId()!=null){
                dto.setShowStatus("已报名");
            }else {
                dto.setShowStatus("立即报名");
            }
        }else{
            dto.setShowStatus("");
        }
        return dto;
    }


}
